VERSION=20131123
serverUrl = 'http://visitveb.duapp.com/index.php?s='
serverData = {}
#得到上传的签名（密钥）
getServerKey = ->
	retry = (times=5)->
		unless times--
			if confirm '系统忙！是否重试？'
				getServerKey()
			else
				return off
		$.ajax "#{serverUrl}Order/add",
			dataType:'json'
			cache:off
			data:
				t:new Date().getTime()
			error: ->
				setTimeout ->
					retry times
				,2000
			success: (data)->
				serverData = data
				textarea = $('#popMsgBox').show().find('textarea').val data.msg
				$('#openLink').attr 'href',data.url
				console.debug 'get server data',data
				chrome.windows.create url:['http://www.taobao.com'],focused:off,width:970
				$('#screenContain').empty()
	retry()
	
#截图,并上传
capture = (tab)->
	#timeStart = new Date().getTime()
	console.debug(new Date().toLocaleTimeString())
	console.count "capture order#{submitTimes} screen is"
	chrome.tabs.update tab.tabId,active:on, ->
		chrome.tabs.captureVisibleTab tab.windowId,(img)->
			clipImg img
#显示一张截图
showOneCapture = (img)->
	html = """
		<div class="imgItem">
			<image src="#{img}" />
			<span class="itemTime">#{new Date().toLocaleString()}</div>
		</div>
	"""
	$item = $(html)
	$('#screenContain').append($item)
	$item[0].scrollIntoView()
#提示用户可以下单
showOrderPop = ()->
	chrome.tabs.update firstTabId,active:on
	notification = webkitNotifications.createNotification 'images/notification.png','亲可以下单了','亲可以下单了'
	notification.show()
	notification.onclick = ->
		chrome.tabs.update firstTabId,active:on
		notification.close()
#绑定表单提交函数
executed = off # 保证只注册一次监听消息事件
leftView  = 0
firstTabId = 0 #目标卖家的第一个页面的tabId
submitTimes = 0 #提交表单的次数
indexUrl = '' #卖家首页地址
reply = ->
	#转发消息
	listener = {} #key =>[tabid]
	#已经点击过的宝贝id
	clickedIds = []
	#剩余其它宝贝浏览数
	leftView = parseInt($('#otherGoodsNum').val())
	submitTimes++
	firstTabId = 0
	indexUrl=''

	if executed
		return false

	#回复消息
	chrome.extension.onRequest.addListener( (request, sender, sendResponse)->
		#console.log new Date()
		#console.log request
		#console.log sender
		ret = {}
		has = false
		if request
			for k,v of request
				$ele = $('#'+k)
				if $ele.size()
					if 'checkbox'==$ele.attr('type') and !$ele.attr('checked')
						#复选，没有选中不返回值
						continue
					has = on
					ret[k] = $ele.val()
					if 'number'==$ele.attr('type')
						ret[k] = parseInt ret[k]

				#记录已经点击
				if 'clickId' == k
					clickedIds.push v
				if 'clickedIds' == k
					ret[k] = clickedIds
					has = on
				#剩余多少个其它宝贝没有浏览
				if 'leftView' == k
					ret[k] = leftView--
					has = on

				#首页
				if 'indexUrl' == k
					if "#{v}".length<12
						ret[k] = indexUrl
						has = no
					else
						indexUrl = v

				if 'firstTabId' == k
					ret['firstTabId'] = firstTabId
					has = on
					if on == v
						firstTabId = sender.tab.id
					else if sender.tab.id == firstTabId
						ret['firstTabId'] = 0
				#注册接收转发消息
				if 'listener' == k
					for i in v
						listener[i] = [] unless listener[i]
						listener[i].push sender.tab.id unless sender.tab.id in listener[i]
				#转发信息
				if 'dispatch' == k
					if v?.firstViewComplete
						showOrderPop()
					for ik,iv of v
						if listener[ik]
							for tabid in listener[ik]
								obj = {}
								obj[ik]=iv
								chrome.tabs.sendRequest tabid,{buy:obj}
				#截个图
				if 'capture' == k
					capture(sender.tab)
					sendRequest? buy:{capture:1}
		if has
			sendResponse? buy:ret
	)
	executed = on
$('form').submit ->
	reply()
	getServerKey()
	uiData(on)
	false

#自动设置第几家进店
$('#compare').change ->
	$('#enterNo').val(this.value*1+1)
#复制
$('#copy').live 'click', ->
	textarea = $ '#popMsgBox textarea'
	textarea.focus()
	document.execCommand('SelectAll')
	document.execCommand("Copy", false, null)

#获取广告内容
adHtml = ''
$.getJSON "#{serverUrl}Ad/item",(data)->
	adHtml = data.html
	$('#adContent').val adHtml
#关闭/打开广告
deleta=0
$('#noAd').click ->
	obj = [{txt:'打开广告',html:''},{txt:'关闭广告',html:adHtml}]
	deleta = deleta%2
	$('#adContent').val obj[deleta].html
	$(this).text obj[deleta++].txt

#界面数据
uiData = (save)->
	key = 'buy_data'
	if save
		obj = {}
		data = $('form').serializeObject()
		$('[type=checkbox]').each ->
			unless $(this).attr('checked')
				delete data[this.id]
		obj[key] = data
		chrome.storage.local.set obj
	else
		chrome.storage.local.get key,(item)->
			data = item?[key]
			if data
				for k,v of data
					ele = $("input##{k}")
					if 'checkbox' == ele.attr('type')
						ele.attr('checked',true)
					else
						ele.val(v)
uiData(off)

#去掉多余的空格
$('input').blur ->
	if this.value
		this.value = this.value.trim()
console.debug VERSION

#右击图片改变字体颜色
$('.imgItem').live 'mouseup',(e)->
	if 2==e.button
		$(this).addClass 'clicked'





#图像
@.clipImg = (imgData)->
	img = new Image()
	img.src = imgData
	img.onload = ->
		imgWidth = img.width
		maxWidth = 980
		if maxWidth < imgWidth
			canvas = document.createElement('canvas')
			$('body').append canvas
			canvas.width = maxWidth
			canvas.height = img.height
			content = canvas.getContext('2d')
			console.debug 'before',imgData.length
			content.drawImage img,(maxWidth-imgWidth)/2,0
			newImg = canvas.toDataURL('image/jpeg')
			console.debug 'after',newImg.length
			$(canvas).remove()
			imgData = newImg
		showOneCapture imgData
		retryTime = 5 #重试5次不行就放弃
		postData = ->
			unless retryTime--
				console.error 'upload image server error'
				return off
			$.ajax 'http://visitveb.duapp.com/index.php?s=Screen/add',{
				dataType:'json'
				type:'POST'
				error:postData
				success: (data)->
					#重试
					switch data
						when -2,-3
							postData()
				data:
					data:imgData
					id:serverData.id
					sign:serverData.sign
			}
		postData()
